package com.awspaas.user.apps.processforsap.impl.send;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.processforsap.model.MessageHeader;
import com.awspaas.user.apps.processforsap.util.HttpClientUtil;
import com.awspaas.user.apps.processforsap.util.ParentInterface;

import java.util.ArrayList;
import java.util.List;

public class SenderSD001Impl extends ParentInterface {

    public SenderSD001Impl(JSONObject jsonObject) {
        super(jsonObject);
    }

    @Override
    public void dueInterFaceData() {
        String result = "";
        try {
            MessageHeader messageHeader = super.messageHeader;
            JSONObject sendData = super.sendData;
            BO configBo = messageHeader.getConfigBo();
            String url = configBo.getString("SEND_URL");
            result = HttpClientUtil.doPost(url, sendData.toJSONString(), SDK.getRuleAPI().executeAtScript("@getSapParamas(PONAME)"), SDK.getRuleAPI().executeAtScript("@getSapParamas(POPASSWORD)"));

            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject newJsonResult =new JSONObject();
            JSONArray jsonArray = jsonObject.getJSONArray("Responses");
            String resultType = "S";
            List<JSONObject> newList = new ArrayList<>();
            for (int i =0;i<jsonArray.size();i++){
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String msgtype= jsonObject1.getString("MSGTYPE");
                if (msgtype.equals("E")){
                    resultType = "E";
                }
                newList.add(jsonObject1);
            }
            //封装最终数据
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("Type",resultType);
            jsonObject1.put("MESSAGE",newList);
            newJsonResult.put("Responses",jsonObject1);
            result = JSONObject.toJSONString(newJsonResult);
        }catch (Exception e) {
            e.printStackTrace();
            super.resultType = false;
            throw new BPMNError("0331",e.getMessage());
        } finally {
            super.resultSendData = sendData.toJSONString();
            super.returnData = result;
        }

    }

}